import { store } from '@/main';
import { useUser } from "@/stores/user";
import { useAccount } from "@/stores/account";
import { SiweMessage } from 'siwe';
import { createSIWEConfig } from '@web3modal/siwe';
import type { SIWECreateMessageArgs, SIWESession, SIWEVerifyMessageArgs } from '@web3modal/core';
import { OptionsController } from '@web3modal/core'
import { callObj } from "@/comm/loginSucCall";
import { Notify } from "@/components/y-notify/script";
import {
    createWeb3Modal,
    defaultConfig,
    useWeb3ModalState,
} from '@web3modal/ethers5/vue';
import { watch, ref } from "vue";
import { post } from "@/comm/request";
import { URL_WALLET_CONTENT, URL_WALLET_NONCE, URL_WALLET_VALIDATE, URL_WALLET_BIND } from '@/comm/api';
import { toast } from "@/components/toast/toast";
// const projectId = '84113507dea067e522655c58ddb66939'
const projectId = import.meta.env.VITE_PROJECT_ID
let replaceID: any;
const chains = [
    {
        chainId: 1,
        name: 'Ethereum',
        currency: 'ETH',
        explorerUrl: 'https://etherscan.io',
        rpcUrl: 'https://cloudflare-eth.com'
    }
]
const mainnet = {
    chainId: 1,
    name: 'Ethereum',
    currency: 'ETH',
    explorerUrl: 'https://etherscan.io',
    rpcUrl: 'https://cloudflare-eth.com'
}
const ethersConfig = defaultConfig({
    metadata: {
        name: 'ChainingView',
        description: 'Connect to ChainingView',
        url: 'https://dev.chainingview.io',
        icons: ['https://avatars.githubusercontent.com/u/37784886']
    },
    defaultChainId: 1,
    rpcUrl: 'https://eth-mainnet.alchemyapi.io/v2/R6mZwt31pb4DdV4cAriiPoxHYJhKcKVa'
})
let statement = 'Sign in With ChainingView'
let connectType = 'login'
const siweConfig = createSIWEConfig({
    createMessage: ({ nonce, address, chainId }: SIWECreateMessageArgs) =>
        new SiweMessage({
            version: '1',
            domain: window.location.host,
            uri: window.location.origin,
            address,
            chainId,
            nonce,
            statement: statement
        }).prepareMessage(),
    getNonce: async () => {
        const nonce = await getNonce()
        if (!nonce) {
            throw new Error('Failed to get nonce!')
        }
        return nonce
    },
    getSession: async (): Promise<any> => {
        const session = await getSession()
        console.log('返回', session)
        if (!session) {
            console.log('Failed to get session!')
            return null
        } else {
            const { address, chainId } = session
            return { address, chainId }
        }
    },
    verifyMessage: async ({ message, signature }: SIWEVerifyMessageArgs) => {
        try {
            const isValid = await validateMessage({ message, signature })
            return isValid
        } catch (error) {
            return false
        }
    },
    onSignIn: async (session?: SIWESession) => {
        try {
            walletJudge()
        } catch (err) {
            console.log('Failed to sign in!', err)
        }
    },
    signOut: async () => {
        try {
            return true
        } catch (error) {
            return false
        }
    }
})
class WalletModal {
    private static instance: WalletModal;
    private modal: any;
    private constructor(loginType?: string | undefined) {
        //判断是否已经登录和登录方式不为钱包 则再次调用的时候应该是为绑定钱包
        if (loginType != 'wallet' && loginType) {
            statement = 'Connect With ChainingView'
            connectType = 'bind'
            console.log('更改为绑定类型！！', connectType, statement)
        }
        this.modal = createWeb3Modal({
            defaultChain: mainnet,
            featuredWalletIds: [
                'c57ca95b47569778a828d19178114f4db188b89b763c899ba0be274e97267d96',
                '1ae92b26df02f0abca6304df07debccd18262fdf5fe82daa81593582dac9a369',
            ],
            excludeWalletIds: ['1ae92b26df02f0abca6304df07debccd18262fdf5fe82daa81593582dac9a369'],
            includeWalletIds: [],
            siweConfig,
            ethersConfig,
            projectId,
            chains,
            themeMode: 'dark',
            themeVariables: {
                '--w3m-accent': "#FCC235",
                '--w3m-color-mix': '#000',
                '--w3m-color-mix-strength': 20
            }
        });
        if (OptionsController.state.metadata) {
            OptionsController.state.metadata.icons = ["https://wallet.chainingview.io/static/images/home-n.png"];
        }
    }
    //重新new一个modal
    public newModal(): any {
        let device = getUser().device?.loginType;
        console.log('重新new!!!!!!!!!!!!!!!!!!!!', device)
        WalletModal.instance = new WalletModal(device);
    }
    public static getInstance(): WalletModal {
        console.log('调用getInstance!!!!!!!!!!!!!!!!!&&&&&&&&&&')
        localStorage.removeItem("@w3m/wallet_id")
        // let device = getUser().device?.loginType;
        // console.log('登录类型', device)
        if (WalletModal.instance) {
            return WalletModal.instance;
        } else {
            WalletModal.instance = new WalletModal();
            return WalletModal.instance;
        }
    }
    public WalletConnect(): void {
        if (this.modal.getIsConnected()) {
            this.modal.disconnect();
            this.modal.open();
        } else {
            this.modal.open();
        }
    }
    public quitWalletLogin(): void {
        if (this.modal) {
            this.modal.disconnect();
        }
        // localStorage.removeItem("walletLogin");
        console.log('modal对象!!!!', this.modal)
    }
    public isWalletConnected(): boolean {
        console.log('调用isWalletConnected!!!!!!!!!!!!!!!!!&&&&&&&&&&', this.modal)
        return this.modal.getIsConnected();
    }
    public getAddress(): string {
        return this.modal.getAddress();
    }
    public getChainId(): number {
        return this.modal.getChainId();
    }
    // 替换弹窗内容
    public startReplaceContent(): void {
        console.log('开始替换内容!!!!!!!!!!!!')
        if (replaceID) {
            clearInterval(replaceID)
        }
        replaceID = setInterval(() => {
            //如果已经替换了内容则关闭轮询
            let res = (window as any).changeIcon()
            // console.log('替换状态',res)
            if (res) {
                clearInterval(replaceID)
            }
        }, 100);
    }
    //关闭轮询
    public stopReplaceContent(): void {
        if (replaceID) {
            clearInterval(replaceID)
        }
    }
}
async function getNonce() {
    try {
        const res: any = await post(URL_WALLET_NONCE)
        if (res?.data) {
            getUser().setUserWalletNonce(res.data)
            return Promise.resolve(res.data)
        } else {
            throw new Error('Failed to get request nonce!!')
        }
    } catch (error) {
        throw new Error('Failed to get nonce!!')
    }
}
const walletModal = WalletModal.getInstance();
function getSession() {
    // console.log('调用getSession!!!!!!!!!!!!!!!!!&&&&&&&&&&',walletModal?.getAddress())
    try {
        const walletSession = localStorage.getItem("walletSession") ? JSON.parse(localStorage.getItem("walletSession") as string) : {};
        console.log('getStorage Session!!!!', walletSession)
        return Promise.resolve({
            address: walletSession?.address,
            chainId: walletSession?.chainId,
        });
    } catch (err) {
        console.log('getSession error', err)
    }
}

async function validateMessage({ message, signature }: any) {
    console.log('交易 validateMessage！！！')
    try {
        let payload = {
            nonce: getUser().walletNonce,
            message: message,
        }
        const baseMessage = btoa(JSON.stringify(payload))
        const prams = {
            payload: baseMessage,
            signature: signature,
        }
        const res: any = await post(URL_WALLET_VALIDATE, prams, true)
        // console.log('校验签名！！',res)
        return Promise.resolve(res?.data)
    } catch (err) {
        throw new Error('Failed to validate message!!')
    }
}
async function walletBind() {
    try {
        let prams = {
            nonce: getUser().walletNonce,
        }
        const res: any = await post(URL_WALLET_BIND, prams, true)
        console.log('钱包绑定！！！！！', res)
        if (res?.code == 200) {
            localStorage.removeItem("@w3m/wallet_id") //清除钱包id 一定要清除这行 不然会一直调起钱包的签名校验
            let err = await getUser().getUserInfo();
            if (!err) {
                Notify.alert(res.info);
            } else {
                Notify.alert(err + "", "warning", 3000);
            }
        } else {
            toast(res?.info,4000)
        }
    } catch (err) {
        console.log('walletBind error', err)
    }
}
async function walletJudge() {
    // console.log('判断钱包操作类型！！！！！', connectType)
    if (connectType == 'login') {
        walletConnect()
    }
    if (connectType == 'bind') {
        walletBind()
    }
}
async function walletConnect() {
    try {
        let prams = {
            nonce: getUser().walletNonce,
            recommendCode: localStorage.getItem('recommendCode') || ''
        }
        const res: any = await post(URL_WALLET_CONTENT, prams, true)
        console.log('链接钱包！！！！', res)
        if (res?.code == 200) {
            localStorage.setItem("token", res.data.token);
            localStorage.removeItem("@w3m/wallet_id") //清除钱包id 一定要清除这行 不然会一直调起钱包的签名校验
            let walletSession = {
                address: walletModal?.getAddress(),
                chainId: walletModal?.getChainId()
            }
            localStorage.setItem("walletSession", JSON.stringify(walletSession));
            if (res.data.firstLogin) {
                setTimeout(() => {
                    getAccount().changePopRegisterSuccess(true);
                }, 200)
            }
            setTimeout(() => {
                getAccount().changePopLogin(false);
                getAccount().changePopRegister(false);
            }, 200);
            let err = await getUser().getUserInfo();
            if (!err) {
                Notify.alert(res.info);
                callObj.callfun();
            } else {
                Notify.alert(err + "", "warning", 2000);
            }
        } else {
            toast(res?.info,4000)
        }
    } catch (err) {
        console.log('walletLogin error', err)
    }
}
const modalState = ref<any>(null)
// 监听弹窗状态
function initModalState() {
    modalState.value = useWeb3ModalState()
}
function getUser() {
    return useUser(store)
}
function getAccount() {
    return useAccount(store)
}
initModalState()
watch(() => modalState.value?.open, (newVal) => {
    console.log('监听Connect弹窗状态', newVal)
    if (newVal) {
        walletModal?.startReplaceContent()
    } else {
        walletModal?.stopReplaceContent()
    }
})
export {
    walletModal
};
